package 领扣_L.两数相加_L2;

import java.util.HashMap;

/**
 * 
 * @author xuliyun
 * @summary	给定两个非空链表来表示两个非负整数。位数按照逆序方式存储，它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
 * 你可以假设除了数字 0 之外，这两个数字都不会以零开头
 */
public class Solution {
		
	public ListNode addTwoNumbers(ListNode l1, ListNode l2){
		ListNode dummy = new ListNode(0);
		int carry = 0;
		ListNode curr = dummy;
		while(l1 != null || l2 != null){
			int x = (l1 != null) ? l1.val : 0;
			int y = (l2 != null) ? l2.val : 0;
			int sum = x + y + carry;
			carry = sum/10;
			curr.next = new ListNode(sum % 10);
			curr = curr.next;
			if(l1 != null ) l1 = l1.next;
			if(l2 != null ) l2 = l2.next;
		}
		if(carry == 1) curr.next = new ListNode(1);
		return dummy.next;
	}
	
	public ListNode addTwoNumbers2(ListNode l1, ListNode l2){
		ListNode dummy;
		ListNode curr = new ListNode(0);
		dummy = curr;
		int i = 0;
		int sum = 0;
        int carry = 0;
		while(l1 != null || l2 != null){
            int x = 0,y = 0;
			if(l1 != null){
				x = l1.val;
				l1 = l1.next;
			}
			if(l2 != null){
				y = l2.val;
				l2 = l2.next;
			}
			
			sum = x + y + carry;
            carry = sum / 10;
            curr.next = new ListNode(sum%10);
            curr = curr.next;
		}
        if(carry == 1) curr.next = new ListNode(1);
		return dummy.next;
	}
}
